package com.datatraffic.broadcastservices;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.commonsware.cwac.locpoll.LocationPollerResult;
import com.datatraffic.databasecontrol.DataSource;
import com.datatraffic.salesup.model.Envio;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.location.Location;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.telephony.TelephonyManager;
import android.util.Log;

public class LocationReceiver extends BroadcastReceiver{

	private String url = "http://www.datatraffic.com.co/salesup/servicio/GPSModule/services/gpsmodule_post.php";
	private DataSource datasource;
	private Context con;
	private SharedPreferences prefs;

	@Override
	public void onReceive(Context context, Intent intent) {

		con=context;
		prefs = PreferenceManager
				.getDefaultSharedPreferences(con.getApplicationContext());
		try
		{
			datasource=new DataSource(context);
			datasource.open();
		}
		catch(Exception ex)
		{
			ex.printStackTrace();

		}

		try {      
			Bundle b=intent.getExtras();

			LocationPollerResult locationResult = new LocationPollerResult(b);

			Location loc=locationResult.getLocation();
			String msg;

			if (loc==null) {
				loc=locationResult.getLastKnownLocation();

				if (loc==null) {
					msg=locationResult.getError();
				}
				else {
					msg="TIMEOUT, lastKnown="+loc.toString();
				}
			}
			else {
				msg=loc.toString();
				Log.i("Location Latitude", String.valueOf(loc.getLatitude()));
				Log.i("Location Longitude", String.valueOf(loc.getLongitude()));
				Log.i("Location Accuracy", String.valueOf(loc.getAccuracy()));
				this.sendData(loc);
			}

			Log.i(getClass().getSimpleName(), "received location: " + msg);   

		}
		catch (Exception e) {
			Log.e(getClass().getName(), e.getMessage());
		}
	}

	public JSONObject convertAndConnect(Location location) {

		Log.e("ENTRA A CONVERTANDO CONNECT","OK");
		String imei="";
		JSONObject loc = new JSONObject();
		try {

			TelephonyManager mngr = (TelephonyManager) con.getSystemService(Context.TELEPHONY_SERVICE);
			imei = mngr.getDeviceId();
			Calendar calendario = Calendar.getInstance();
			int hora, minutos, segundos,dia,mes,anio;
			hora =calendario.get(Calendar.HOUR_OF_DAY);
			minutos = calendario.get(Calendar.MINUTE);
			segundos = calendario.get(Calendar.SECOND);
			dia =calendario.get(Calendar.DAY_OF_MONTH);
			mes = calendario.get(Calendar.MONTH)+1;
			anio = calendario.get(Calendar.YEAR);
			String fecha=String.valueOf(anio)+"-"+String.valueOf(mes)+"-"+String.valueOf(dia)+" "+String.valueOf(hora)+":"+String.valueOf(minutos)+":"+String.valueOf(segundos);

			
			String userId=prefs.getString("idUsuario", "");
			
			JSONArray jArray = new JSONArray();
			JSONObject objTmp=new JSONObject();
			objTmp.put("function", "reportPosition");
			objTmp.put("mobile_key", "");
			objTmp.put("resource", imei);
			objTmp.put("user", userId);


			JSONObject objOk=new JSONObject();
			objOk.put("date_time", fecha);
			objOk.put("latitude", String.valueOf(location.getLatitude()));
			objOk.put("longitude", String.valueOf(location.getLongitude()));
			objOk.put("speed", String.valueOf(location.getSpeed()));
			objOk.put("heading", String.valueOf(location.getBearing()));
			objOk.put("precision", String.valueOf(location.getAccuracy()));
			jArray.put(objOk);
			objTmp.put("data", jArray);

			loc=objTmp;

		} catch (JSONException e) {
			e.printStackTrace();
		}

		try
		{
			String response = postLocation(loc,imei);
			loc=new JSONObject(response);
		}
		catch(Exception ex)
		{
			ex.printStackTrace();

		}
		return loc;
	}

	public String postLocation(JSONObject location,String imei) {
		String obj = "";
		try {

			ConnectivityManager connManager = (ConnectivityManager) con.getSystemService(Context.CONNECTIVITY_SERVICE);
			NetworkInfo mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
			NetworkInfo mMobile = connManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);

			if(mMobile.isAvailable() == true)
			{
				Log.e("OIGA!!!","ENTRO POR 3G");
				if(datasource.verifica()==false)
				{
					Log.e("OIGA!!!","VA A HACER EL POST");
					obj = postToServer(location);
					JSONObject resultado=new JSONObject(obj);
					if(resultado!=null && resultado.has("error") && resultado.getString("error").equalsIgnoreCase("true"))
					{
						Envio envio=new Envio();
						envio.setFunction(location.getString("function"));
						envio.setLatitude(location.getString("latitude"));
						envio.setLongitude(location.getString("longitude"));
						envio.setPrecision(location.getString("precision"));
						envio.setResource(location.getString("resource"));
						envio.setDatetime(location.getString("date_time"));
						envio.setMobilekey(location.getString("mobile_key"));
						envio.setSpeed(location.getString("speed"));
						envio.setHeading(location.getString("heading"));
						envio.setUser(location.getString("user"));

						datasource.insertEncuesta(envio);
					}
				}
				else
				{
					Log.e("OIGA!!!","VA A BUSCAR EN LA BASE DE DATOS");
					JSONArray jArray = new JSONArray();
					JSONObject objTmp=new JSONObject();
					objTmp.put("function", "reportPosition");
					objTmp.put("mobile_key", "");
					objTmp.put("resource", imei);
					ArrayList<Envio> envios=datasource.getAll();
					for(Envio env:envios)
					{

						JSONObject objOk=new JSONObject();
						objOk.put("date_time", env.getDatetime());
						objOk.put("latitude", env.getLatitude());
						objOk.put("longitude", env.getLongitude());
						objOk.put("speed", env.getSpeed());
						objOk.put("heading", env.getHeading());
						objOk.put("precision", env.getPrecision());
						objOk.put("user",env.getUser());
						jArray.put(objOk);

					}

					objTmp.put("data", jArray);
					obj = postToServer(objTmp);
					if(obj.equalsIgnoreCase("ok"))
					{
						datasource.deleteTable();
					}


				}
			}
			else
			{
				if (mWifi.isAvailable() == true)
				{
					Log.e("OIGA!!!","ENTRA POOR WIFI");
					if(datasource.verifica()==false)
					{
						Log.e("OIGA!!!","VA A HACER EL POST DESDE WIFI");
						obj = postToServer(location);
						JSONObject resultado=new JSONObject(obj);
						if(resultado!=null && resultado.has("error") && resultado.getString("error").equalsIgnoreCase("true"))
						{
							Envio envio=new Envio();
							envio.setFunction(location.getString("function"));
							envio.setLatitude(location.getString("latitude"));
							envio.setLongitude(location.getString("longitude"));
							envio.setPrecision(location.getString("precision"));
							envio.setResource(location.getString("resource"));
							envio.setDatetime(location.getString("date_time"));
							envio.setMobilekey(location.getString("mobile_key"));
							envio.setSpeed(location.getString("speed"));
							envio.setHeading(location.getString("heading"));
							envio.setUser(location.getString("user"));

							datasource.insertEncuesta(envio);
						}
					}
					else
					{
						Log.e("OIGA!!!","GUARDA EN BASE DE DATOS DESDE WIFI");
						JSONArray jArray = new JSONArray();
						JSONObject objTmp=new JSONObject();
						objTmp.put("function", "reportPosition");
						objTmp.put("mobile_key", "");
						objTmp.put("resource", imei);
						ArrayList<Envio> envios=datasource.getAll();
						for(Envio env:envios)
						{

							JSONObject objOk=new JSONObject();
							objOk.put("date_time", env.getDatetime());
							objOk.put("latitude", env.getLatitude());
							objOk.put("longitude", env.getLongitude());
							objOk.put("speed", env.getSpeed());
							objOk.put("heading", env.getHeading());
							objOk.put("precision", env.getPrecision());
							objOk.put("user", env.getUser());
							jArray.put(objOk);

						}

						objTmp.put("data", jArray);
						obj = postToServer(objTmp);
						if(obj.equalsIgnoreCase("ok"))
						{
							datasource.deleteTable();
						}
					}
				}
				else
				{
					Log.e("OIGA!!!","INSERTA EN BASE DE DATOS");
					Envio envio=new Envio();

					envio.setFunction(location.getString("function"));
					envio.setLatitude(location.getString("latitude"));
					envio.setLongitude(location.getString("longitude"));
					envio.setPrecision(location.getString("precision"));
					envio.setResource(location.getString("resource"));
					envio.setDatetime(location.getString("date_time"));
					envio.setMobilekey(location.getString("mobile_key"));
					envio.setSpeed(location.getString("speed"));
					envio.setHeading(location.getString("heading"));
					envio.setUser(location.getString("user"));

					datasource.insertEncuesta(envio);

				}
			}


		} catch (Exception e) {
			e.printStackTrace();
			Log.e("Servicio XXX","SUCEDIO UN ERROR 1", e);

		}
		return obj;
	}

	public String postToServer(JSONArray json){

		String jsonResultStr="";
		Log.e("A ENVIAR", json.toString());
		HttpPost httppost = new HttpPost(url);
		HttpParams httpparams = new BasicHttpParams();
		HttpConnectionParams.setConnectionTimeout(httpparams, 30000);
		HttpConnectionParams.setSoTimeout(httpparams, 30000);
		HttpClient httpclient = new DefaultHttpClient(httpparams);
		try {

			httppost.setHeader("json", json.toString());
			httppost.getParams().setParameter("information", json.toString());

			HttpResponse response = httpclient.execute(httppost);
			jsonResultStr= EntityUtils.toString(response.getEntity());

			Log.e("Resultado", jsonResultStr);
		}

		catch(Exception ex)
		{
			Log.e("SUCEDIO UN ERROR", ex.getMessage());
		}


		return jsonResultStr;

	}
	
	private String postToServer(JSONObject json) throws Exception {
		HttpClient client = new DefaultHttpClient();
		HttpPost post = new HttpPost(url);
		List<NameValuePair> pairs = new ArrayList<NameValuePair>();
		pairs.add(new BasicNameValuePair("information", json.toString()));
		post.setEntity(new UrlEncodedFormEntity(pairs));
		HttpResponse response = client.execute(post);
		BufferedReader reader = new BufferedReader(new InputStreamReader(
				response.getEntity().getContent(), "UTF-8"));
		String jsonResultStr = reader.readLine();
		Log.e("Resultado", jsonResultStr);
		return jsonResultStr;
	}

	
	private void sendData(final Location cordenada) {

		final AsyncTask<Void, Void, Boolean> send = new AsyncTask<Void, Void, Boolean>() {

		    private  JSONObject res;
			@Override
			protected void onPreExecute() {
				
			}

			@Override
			protected Boolean doInBackground(Void... params) {
				JSONObject result = convertAndConnect(cordenada);
				try {
					if (result!=null && !result.getBoolean("error"))
					{
						res=result;
						return true;
					}
					else
						return false;
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				return false;
			}

			@Override
			protected void onPostExecute(Boolean result2) {
				if (!result2) {
					
				} else {
					
					Log.i("RESULTADO DEL ENVIO", res.toString());
					
				}
			}
		};
		send.execute();
	}

}
